package com.hy.dubboconsumer.service;


import com.hy.common.Service.UserService;
import com.hy.common.pojo.User;
import org.apache.dubbo.common.stream.StreamObserver;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.io.Serializable;

/**
 * @author: 王富贵
 * @description:
 * @createTime: 2022年10月04日 21:06:32
 */
@Service
public class OrderService implements Serializable {
    @DubboReference
    private UserService userService;

    public String createOrder() {
        User user = userService.getUser(6905);
        System.out.println("成功创建订单");

        return user.toString() + "已经成功为用户创建订单";
    }

    public String getServiceStreamData() {
        //服务端流，消费方不停的接收响应
        userService.sayHelloServerStream("hello", new StreamObserver<String>() {
            //接收响应处理程序
            @Override
            public void onNext(String data) {
                System.out.println("接受到结果：" + data);
            }

            //接收错误处理程序
            @Override
            public void onError(Throwable throwable) {
                System.out.println("服务提供方报错了");
            }

            //接收完成处理参数
            @Override
            public void onCompleted() {
                System.out.println("服务端响应结束，现在是我接收端");
            }
        });

        return "";
    }

    public StreamObserver<String> getStreamData() {

        //接收流式响应
        StreamObserver<String> request = userService.sayHelloStream(new StreamObserver<String>() {
            @Override
            public void onNext(String data) {
                System.out.println(data);
            }

            @Override
            public void onError(Throwable throwable) {
                throwable.printStackTrace();
            }

            @Override
            public void onCompleted() {
                System.out.println("终止请求");
            }
        });

        //再次请求
        for (int i = 0; i < 10; i++) {
            request.onNext("消费方请求" + i);
        }

        //终止连接
        request.onCompleted();

        return request;
    }
}
